<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title"
      :width="modalWidth"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :visible="visible"
      @ok="handleOk"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleCancel">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </template>
      <a-row :gutter="24">
        <a-col :span="5">
          <div class="treeBox">
            <a-tree
              v-if="treeData.length > 0"
              :tree-data="treeData"
              :show-line="true"
              :selected-keys="selectedKeys"
              :replaceFields="replaceFields"
              :load-data="onLoadData"
              @select="handleSelect"
            >
            </a-tree>
          </div>
        </a-col>
        <a-col :span="19">
          <a-table
            :columns="wareColumns"
            :data-source="tableData"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            bordered
            :rowKey="(record, index) => record.id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
              type: 'radio',
            }"
          >
          </a-table>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import { wareColumns } from "./tableConfig";
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";

export default {
  mixins: [tableMinxins],
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 1677, // 抽屉宽度
      model: {},
      treeData: [],
      selectedKeys: [],
      shelfId: null,
      replaceFields: { children: "children", title: "title", key: "index" },
      tableOption: [],
      wareColumns,
    };
  },
  methods: {
    modalAdd() {
      this.modalEdit(this.model);
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.getTreeData();
      this.visible = true;
      this.model = Object.assign({}, record);
      if (this.selectedRowKeys.length > 0) {
        let id = this.selectedRowKeys[0];
        if (id !== undefined) {
          this.getShelfPage(id);
        }
      } else {
        this.getShelfPage();
      }
    },
    // 获取全部仓库
    async getTreeData() {
      var params = { pageNumber: 1, pageSize: 999999, deleteFlag: "N" };
      const res = await api.wareHousePage(params);
      this.treeData = res.data.data.map((item, index) => {
        return {
          key: item.id,
          title: item.wareHouseName,
          type: res.data.type,
          isLeaf: false,
          index: `${index}-${item.id}`,
        };
      });
    },

    // 级联查询（货区）
    async getShelfAreaCargo(id) {
      const res = await api.shelfAreaCargo({ id });
      let result = res.data.data;
      if (result.length > 0) {
        return result.map((item, index) => {
          return {
            title: `${item.serialNumber}`,
            key: item.id,
            type: res.data.type,
            isLeaf: false,
            index: `${index}-${item.id}`,
          };
        });
      }
    },
    // 级联查询 （货架）
    async getShelfAreaRemainList(id) {
      const res = await api.shelfAreaRemainList({ id });
      let result = res.data.data;
      if (result.length > 0) {
        return result.map((item, index) => {
          return {
            title: `${item.serialNumber}`,
            key: item.id,
            type: res.data.type,
            isLeaf: true,
            index: `${index}-${item.id}`,
          };
        });
      }
    },
    // 分页、排序、筛选变化时触发
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.pagination.pageNumber = pagination.current;
      if (this.selectedRowKeys.length > 0) {
        let id = this.selectedRowKeys[0];
        let shelfAreaId = this.selectedKeys[0].split("-")[1];
        this.getShelfPage(id, shelfAreaId);
      } else {
        this.getShelfPage();
      }
    },
    // 查询 （库位）
    async getShelfPage(id, shelfAreaId) {
      let { pageNumber, pageSize } = this.pagination;
      let params = { findAll: -1, pageNumber, pageSize };
      if (id) {
        params.findAll = 1;
        params.shelfIdList = [];
        params.shelfIdList.push(id);
      }
      if (shelfAreaId) {
        delete params.shelfIdList;
        params.shelfAreaId = shelfAreaId;
      }
      const res = await api.ShelfPage(params);
      this.tableData = res.data.data;
      this.pagination.total = res.data.total;
    },
    handleSelect(selectedKeys, e) {
      this.selectedKeys = selectedKeys;
      if (e.node.dataRef.type === "shelfArea") {
        this.pagination.pageNumber = 1;
        this.pagination.current = 1;
        this.getShelfPage(null, e.node.dataRef.key);
      }
    },
    async onLoadData(treeNode) {
      if (treeNode.dataRef.children) {
        return;
      }
      // 货区
      if (treeNode.dataRef.type === "wareHouse") {
        treeNode.dataRef.children = await this.getShelfAreaCargo(
          treeNode.dataRef.key
        );
      }
      // 货架
      if (treeNode.dataRef.type === "stockArea") {
        treeNode.dataRef.children = await this.getShelfAreaRemainList(
          treeNode.dataRef.key
        );
      }
      this.treeData = [...this.treeData];
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.tableOption = selectedRows.map((item) => {
        this.shelfId = item.id;
        return {
          value: item.id,
          label: item.label,
        };
      });
    },
    handleOk(e) {
      this.$emit("ReceiptSelect", this.shelfId, this.tableOption);
      this.visible = false;
      this.model = {};
      this.pagination.current = 1;
      this.pagination.pageNumber = 1;
      this.selectedRowKeys = [];
      this.selectedKeys = [];
      this.tableData = [];
    },
    handleCancel() {
      this.visible = false;
      this.model = {};
      this.pagination.current = 1;
      this.pagination.pageNumber = 1;
      this.selectedKeys = [];
      this.selectedRowKeys = [];
      this.tableData = [];
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 1677;
      }
    },
  },
};
</script>
